package spring.cloud.tasks.executor.name_space.executor.task.task_listener.task_configuration;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import spring.cloud.tasks.executor.name_space.executor.task.task_listener.TreeCacheListener;
import spring.cloud.tasks.executor.utils.LogUtils;

/**
 * 任务删除
 */
@Slf4j
@Setter
@Getter
public class DisableTaskListener extends TreeCacheListener {

    private final TaskConfigurationListenerHolder taskConfigurationListenerHolder;

    public DisableTaskListener(TaskConfigurationListenerHolder taskConfigurationListenerHolder) {
        this.taskConfigurationListenerHolder = taskConfigurationListenerHolder;
    }

    @Override
    protected void dataChanged(CuratorFramework curatorFramework, String path, TreeCacheEvent treeCacheEvent) {
        if (taskConfigurationListenerHolder.isShutdown) {
            return;
        }
        //Enabled不在这进行处理。由调度器进行监听
        if (TaskConfigurationNode.isEnabledPath(taskConfigurationListenerHolder.taskId, path) &&//
                (TreeCacheEvent.Type.NODE_REMOVED == treeCacheEvent.getType() ||//
                        treeCacheEvent.getData() != null && "DISABLE".equals(new String(treeCacheEvent.getData().getData())))) {
            LogUtils.info(log, taskConfigurationListenerHolder.taskId, "job is going to be deleted.");
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        taskConfigurationListenerHolder.taskExecutor.shutdown();
                    } catch (Throwable t) {
                        LogUtils.error(log, taskConfigurationListenerHolder.taskId, "delete job error", t);
                    }
                }
            });
            thread.setName(taskConfigurationListenerHolder.executorId + "-" + taskConfigurationListenerHolder.taskId + "-taskDelete");
            thread.start();
        }
    }
}
